//
//  OwaClient.m
//  UrlTest
//
//  Created by Sandeep Mistry on 13/07/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "MailData.h"

#import "OwaClient.h"


@implementation OwaClient

- (id)initWithHost:(NSString*)newHost username:(NSString*)newUsername password:(NSString*)newPassword;
{
	self = [super init];
	
	host = newHost;
	username = newUsername;
	password = newPassword;
	
	baseUrl = [NSString stringWithFormat:@"https://%@/", host];
	authUrl = [baseUrl stringByAppendingString:@"/exchweb/bin/auth/owaauth.dll"];
	exchangeUrl = [baseUrl stringByAppendingString:@"exchange/"];
	userUrl = [exchangeUrl stringByAppendingString:username];
	
	[host retain];
	[username retain];
	[password retain];
	
	return self;
}

- (void)dealloc
{
	[host release];
	[username release];
	[password release];
	
	[super dealloc];
}

- (BOOL) login
{
	NSString* loginPostString =[NSString stringWithFormat:@"destination=%@&username=%@&password=%@&flags=4", exchangeUrl, username, password];
	NSData* loginPostData = [loginPostString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
	NSString* loginPostLength = [NSString stringWithFormat:@"%d", [loginPostData length]];

	NSMutableURLRequest* loginRequest = [[[NSMutableURLRequest alloc] init] autorelease];
	[loginRequest setURL:[NSURL URLWithString:authUrl]];
	[loginRequest setHTTPMethod:@"POST"];
	[loginRequest setValue:host forHTTPHeaderField:@"Host"];
	[loginRequest setValue:loginPostLength forHTTPHeaderField:@"Content-Length"];
	[loginRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
	[loginRequest setHTTPBody:loginPostData];
	
	NSError* loginError;
	NSData* loginData;
	NSHTTPURLResponse* loginResponse;
	
	loginData = [NSURLConnection sendSynchronousRequest:loginRequest returningResponse:&loginResponse error:&loginError];
	
	if(200 !=[loginResponse statusCode])
	{
		return false;
	}
	
	NSString* inboxUrlString =@"<?xml version=\"1.0\" encoding=\"utf-8\" ?><D:propfind xmlns:D=\"DAV:\" xmlns:a=\"urn:schemas:httpmail:\"><D:prop><a:inbox/></D:prop></D:propfind>";
	NSData* inboxUrlPostData = [inboxUrlString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
	NSString* inboxUrlPostLength = [NSString stringWithFormat:@"%d", [inboxUrlPostData length]];

	NSMutableURLRequest* inboxUrlRequest = [[[NSMutableURLRequest alloc] init] autorelease];
	[inboxUrlRequest setURL:[NSURL URLWithString:userUrl]];
	[inboxUrlRequest setHTTPMethod:@"PROPFIND"];
	[inboxUrlRequest setValue:host forHTTPHeaderField:@"Host"];
	[inboxUrlRequest setValue:inboxUrlPostLength forHTTPHeaderField:@"Content-Length"];
	[inboxUrlRequest setValue:@"text/xml" forHTTPHeaderField:@"Content-Type"];
	[inboxUrlRequest setValue:@"0" forHTTPHeaderField:@"Depth"];
	[inboxUrlRequest setHTTPBody:inboxUrlPostData];
	
	NSError* inboxUrlError;
	NSData* inboxUrlData;
	NSHTTPURLResponse* inboxUrlResponse;
	
	inboxUrlData = [NSURLConnection sendSynchronousRequest:inboxUrlRequest returningResponse:&inboxUrlResponse error:&inboxUrlError];
	
	if(207 != [inboxUrlResponse statusCode])
	{
		return false;
	}
	
	if([inboxUrlData length] <= 0)
	{
		return false;
	}
	
	NSError* inboxUrlXmlDocError;
	NSXMLDocument* inboxUrlXmlDoc = [[[NSXMLDocument alloc] initWithData:inboxUrlData options:0 error:&inboxUrlXmlDocError] autorelease];

	if(nil == inboxUrlXmlDoc)
	{
		return false;
	}
	
	NSArray* inboxNodes = [inboxUrlXmlDoc nodesForXPath:@"/a:multistatus/a:response/a:propstat/a:prop/d:inbox" error:&inboxUrlXmlDocError];
	
	if([inboxNodes count] <= 0)
	{
		return false;
	}
	
	inboxUrl = [[inboxNodes objectAtIndex:0] stringValue];
	
	return true;
}

- (NSArray*) checkInbox
{
	NSString* checkNewMailString = @"<?xml version=\"1.0\" encoding=\"utf-8\" ?><searchrequest xmlns=\"DAV:\"><sql>SELECT \"urn:schemas:httpmail:fromemail\", \"urn:schemas:httpmail:read\"FROM \"\"WHERE &quot;DAV:iscollection&quot; = False AND &quot;DAV:ishidden&quot; = False AND \"urn:schemas:httpmail:read\"= False ORDER BY \"DAV:creationdate\"</sql></searchrequest>";

	NSData* checkNewMailPostData = [checkNewMailString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
	NSString* checkNewMailPostLength = [NSString stringWithFormat:@"%d", [checkNewMailPostData length]];

	NSMutableURLRequest* checkNewMailRequest = [[[NSMutableURLRequest alloc] init] autorelease];
	[checkNewMailRequest setURL:[NSURL URLWithString:inboxUrl]];
	[checkNewMailRequest setHTTPMethod:@"SEARCH"];
	[checkNewMailRequest setValue:host forHTTPHeaderField:@"Host"];
	[checkNewMailRequest setValue:checkNewMailPostLength forHTTPHeaderField:@"Content-Length"];
	[checkNewMailRequest setValue:@"text/xml" forHTTPHeaderField:@"Content-Type"];
	[checkNewMailRequest setHTTPBody:checkNewMailPostData];
	
	NSError* checkNewMailError;
	NSData* checkNewMailData;
	NSHTTPURLResponse* checkNewMailResponse;
	
	checkNewMailData = [NSURLConnection sendSynchronousRequest:checkNewMailRequest returningResponse:&checkNewMailResponse error:&checkNewMailError];
	
	if(207 != [checkNewMailResponse statusCode])
	{
		return nil;
	}
	
	if([checkNewMailData length] <= 0)
	{
		return nil;
	}
	
	NSError* checkNewMailXmlDocError;
	NSXMLDocument* checkNewMailXmlDoc = [[[NSXMLDocument alloc] initWithData:checkNewMailData options:0 error:&checkNewMailXmlDocError] autorelease];

	if(nil == checkNewMailXmlDoc)
	{
		return nil;
	}
	
	NSArray* newMailUrlNodes = [checkNewMailXmlDoc nodesForXPath:@"/a:multistatus/a:response/a:href" error:&checkNewMailXmlDocError];
	NSArray* newMailFromNodes = [checkNewMailXmlDoc nodesForXPath:@"/a:multistatus/a:response/a:propstat/a:prop/d:fromemail" error:&checkNewMailXmlDocError];
	
	NSMutableArray* newMails = [[[NSMutableArray alloc] initWithCapacity:[newMailUrlNodes count]] autorelease];
	
	int i;
	for(i = 0; i < [newMailUrlNodes count]; i++)
	{
		NSString* newMailUrl = [[newMailUrlNodes objectAtIndex:i] stringValue];
		
		NSString* newMailSubject = [newMailUrl substringToIndex:([newMailUrl length] - 4)];// stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
		newMailSubject = [newMailSubject substringFromIndex:([inboxUrl length] + 1)];
		newMailSubject = [newMailSubject stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
		
		NSString* newMailFrom = [[newMailFromNodes objectAtIndex:i] stringValue];
		
		MailData* newMailData = [[[MailData alloc] initWithSubject:newMailSubject from:newMailFrom] autorelease];
		[newMails addObject:newMailData];
	}
	
	return newMails;
}

@end
